<template>
<!--	<div class="h-full flex items-center">-->
    <!--<div class="flex-1 flex items-center pr-4">-->
      <!--<span class="text-sm text-666 mr-2">区域选择</span>-->
      <!--<el-input placeholder="请选择区域信息"-->
                <!--style="width: 540px;"-->
                <!--class="filter-item"-->
                <!--size="mini"-->
                <!--:suffix-icon="showTree?'el-icon-arrow-up':'el-icon-arrow-down'"-->
                <!--@click.native="deptogglePanel($event)"-->
                <!--v-model="currentbuildInfo.buildingName">-->
      <!--</el-input>-->
      <!--<div v-show="showTree" class="objectTree1 w-1601" ref="suoShuMenTree">-->
        <!--<el-tree-->
          <!--:style="'height:'+containerHeight+'px'"-->
          <!--ref="buildTree"-->
          <!--highlight-current-->
          <!--node-key="buildingId"-->
          <!--:check-on-click-node="true"-->
          <!--:check-strictly="true"-->
          <!--show-checkbox-->
          <!--:data="dataList"-->
          <!--:expand-on-click-node="false"-->
          <!--:props="menuListTreeProps"-->
          <!--@check-change="selectBuild"-->
          <!--default-expand-all-->
        <!--&gt;</el-tree>-->
      <!--</div>-->

      <!--&lt;!&ndash;<el-cascader  v-model="currentbuildInfo" :options="buildings" :props="{ checkStrictly: true, value: 'buildingId', label: 'buildingName' }" size="small" class="flex-1"></el-cascader>&ndash;&gt;-->
    <!--&lt;!&ndash;&ndash;&gt;-->
    <!--</div>-->
<!--	</div>-->
</template>

<script>
  import * as Util from "@/utils";
  import util from '@/libs/util'
  import {parseSvg} from '@topology/svg'
  import list2tree from 'list2tree'
  import color from "../../../store/modules/d2admin/modules/color";
  import axios from 'axios'

	export default {
		data() {
			return {
        socket: null,
        pen:"",
        realMeterCodes:[],
        menuListTreeProps: {
          label: "buildingName",
          children: "children"
        },
        dataList: [],
        showTree:false,
        currentbuildInfo: {
          buildingName:'',
        },
				isMinimapActive: false,
        buildings: [],
        currentbuildInfo:[64,65],
        wkq: {
          url: "http://" + window.location.hostname + ":8012/images/wkq.svg",
          type: 'wkq',
          str: ''
        },
        meter: {
          url: "http://" + window.location.hostname + ":8012/images/meter.svg",
          type:'meter',
          str: ''
        }
			}
		},
    created() {

      this.getSvgdetie(this.wkq.url,this.wkq.type);
      this.getSvgdetie(this.meter.url,this.meter.type);
      this.$nextTick(() => {
        this.connect();
        this.getBuildings()
      })

    },
    computed: {
      containerHeight() {
        return Util.getClientHeight() - 143;
      },
      bottomChartHeight(){
        return Util.getClientHeight() - 340;
      },
      event() {
        return this.$store.state.event.event
      }
    },
    beforeDestroy() {
      if (this.socket) {
        console.log("beforeDestroy webSocketServer close");
        this.socket.close(); // 关闭连接
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.socket) {
        console.log("webSocketServer close");
        this.socket.close()
        next()
      }
    },
		methods: {
      connect() {
        let baseUrl = process.env.VUE_APP_API
        if(baseUrl.indexOf("http")!= -1) {
          console.log(11111111, baseUrl.replace('http', 'ws') + 'webSocketServer')
          this.socket = new WebSocket(baseUrl.replace('http', 'ws') + 'webSocketServer');
        }else{
          baseUrl = "ws://"+window.location.hostname+":8012/webSocketServer";
          console.log(22222, baseUrl)
          this.socket = new WebSocket(baseUrl);
        }


        this.socket.onopen = () => {
          console.log('WebSocket connection established');
        };

        this.socket.onmessage = (event) => {
          const res = JSON.parse(event.data);
          console.log(22222222,res.data)
          for (var i = 0; i < this.pen.pens.length; i++) {
            if (this.realMeterCodes.indexOf(this.pen.pens[i].metercode) == -1) {
              continue
            }
            let color = 'red'
            let image = this.pen.pens[i].image
            if (res.data[this.pen.pens[i].metercode]) {
              color = 'green'
              if(this.pen.pens[i].key=='wkq'){
                let value = res.data[this.pen.pens[i].metercode].find(i=> i.collectType == '080001')
                if(value) {
                  image = this.changeSvg(this.wkq.str, value.oval, '', 'wkq')
                }
              }
              if(this.pen.pens[i].key=='meter'){
                image  = this.changeSvg(this.meter.str,'',color,'meter')
              }
            }else{
              if(this.pen.pens[i].key=='wkq'){
                image = this.changeSvg(this.wkq.str,'','red','wkq')
              }
              if(this.pen.pens[i].key=='meter'){
                image  = this.changeSvg(this.meter.str,'',color,'meter')
              }
            }

            topology.setValue({
              id: this.pen.pens[i].id,
              iconColor: color,
              background: color,
              color: color,
              image: image
            })
          }
        };

        this.socket.onerror = (error) => {
          console.error('WebSocket error:', error);
        };

        this.socket.onclose = () => {
          console.log('WebSocket connection closed');
        };
      },
      sendMessage(param) {
        //实时监测
        this.socket.send(JSON.stringify({ messType:"zutaishow",messContent: param }));
      },

      async open() {
        window.showtopology.open({"pens":[]});
        this.mycomponents = [];

        let idval = this.$route.query.id
        if (typeof(idval) != "undefined"){
          this.$api.okhttp({
            url: this.$http.adornUrl("/topologies/find"),
            method: "get",
            params: this.$http.adornParams({
              id: idval,
              customerId: this.$util.cookies.get("customer_id")
            })
          }).then((data) => {
            if (data && data.code === 0 && data.obj) {
              this.bgurl = data.obj.bgurl
              this.id = data.obj.id
              this.name = data.obj.name
              this.pen = JSON.parse(data.obj.data)
              this.pen.locked = 2;
              let meterCodes = []
              for (var i = 0; i < this.pen.pens.length; i++) {
                if(this.pen.pens[i].metercode && this.pen.pens[i].metercode !== '') {
                  meterCodes.push(this.pen.pens[i].metercode)
                }
              }
              if(meterCodes.length ==0){
                return
              }

              this.$api.checkMeterData({
                customerId: JSON.parse(this.$util.cookies.get('user')).customer_id,
                meterCodes: meterCodes,
              }).then(res1 => {
                let realMeterCodes = res1.data
                if(realMeterCodes && realMeterCodes.length > 0 ) {
                  this.realMeterCodes = realMeterCodes
                    this.$api.getMeterData({
                      customerId: JSON.parse(this.$util.cookies.get('user')).customer_id,
                      meterCodes: realMeterCodes,
                    }).then(res => {
                      for (var i = 0; i < this.pen.pens.length; i++) {
                        if (realMeterCodes.indexOf(this.pen.pens[i].metercode) == -1) {
                          continue
                        }
                        if (res.data[this.pen.pens[i].metercode]) {
                          //  this.pen.pens[i].text = res.data[this.pen.pens[i].id][0].collectName
                          this.pen.pens[i].background = 'green'
                          this.pen.pens[i].color = 'green'
                          this.pen.pens[i].iconColor = 'green'
                          if(this.pen.pens[i].key=='wkq'){
                            let value = res.data[this.pen.pens[i].metercode].find(i=> i.collectType == '080001')
                            if(value) {
                              this.pen.pens[i].image = this.changeSvg(this.wkq.str, value.oval, '', 'wkq')
                            }
                          }else if(this.pen.pens[i].key=='meter'){
                            this.pen.pens[i].image  = this.changeSvg(this.meter.str,'','green','meter')
                          }

                        } else {
                          this.pen.pens[i].background = 'red'
                          this.pen.pens[i].color = 'red'
                          this.pen.pens[i].iconColor = 'red'
                          if(this.pen.pens[i].key=='wkq'){
                            this.pen.pens[i].image = this.changeSvg(this.wkq.str,'','red','wkq')
                          }else if(this.pen.pens[i].key=='meter'){
                            this.pen.pens[i].image  = this.changeSvg(this.meter.str,'','red','meter')
                          }
                        }
                      }
                      window.showtopology.open(this.pen)
                      window.showtopology.fitView(false,10)

                      //发送websocket消息
                      this.sendMessage({
                        customerId: JSON.parse(this.$util.cookies.get('user')).customer_id,
                        meterCodes: realMeterCodes,
                      })
                    })
                }else{
                  window.showtopology.open(this.pen)
                  window.showtopology.fitView(false,10)
                }
              })
            }else{
              window.showtopology.open(this.pen)
              window.showtopology.fitView(false,10)
            }
          });
        }
      },

      async getSvgdetie(svgUrl,type){
       await axios.get(svgUrl).then(res => {
          // return parseSvg(res.data)
         if(type == 'wkq'){
           this.wkq.str = res.data
         }else if(type == 'meter'){
           this.meter.str = res.data
         }
        })
      },

      convertStrTosvg(svg){
          const encodedSvg = encodeURIComponent(svg)
            .replace(/%([0-9A-F]{2})/g, (match, p1) =>
              String.fromCharCode('0x' + p1));
          return `data:image/svg+xml;base64,${btoa(encodedSvg)}`;
      },

      changeSvg(svgString1,value,color,type){
        // const svgString = atob(this.convertStrTosvg(svgString1).split(',')[1])
        // console.log(2222,svgString)
        //解析为 JSON
        const parser = new DOMParser();
        const svgDoc = parser.parseFromString(svgString1, "image/svg+xml");
        const svgElement = svgDoc.querySelector("svg");
        const svgJson = {
          width: svgElement.getAttribute("width"),
          height: svgElement.getAttribute("height"),
          viewBox: svgElement.getAttribute("viewBox"),
          xmlns: svgElement.getAttribute("xmlns"),
          children: Array.from(svgElement.children).map(child => {
           let obj = {
              tag: child.tagName.toLowerCase(),
              attrs: Object.fromEntries(
                Array.from(child.attributes).map(attr => [attr.name, attr.value])
              ),
              content: child.textContent
            }
            if(type=='wkq'){
                if(obj.attrs.id === "tempValue"){
                  obj.content = value;
                }
                if(obj.tag === "rect" && color != ''&& obj.attrs.id == 'bg' ){
                  obj.attrs.fill = color;
                }
            }
            if(type=='meter'){
              if(obj.tag === "path" && color != ''){
                obj.attrs.fill = color;
              }
            }

            return obj
          })
        };
       // 3. 修改 tempValue
       //  const tempValueText = svgJson.children.find(child =>
       //    child.tag === "text" && child.attrs.id === "tempValue"
       //  );
       //
       //
       //  if (tempValueText) tempValueText.content = "23";
        const updatedSvg = this.jsonToSvg(svgJson);
        const newSvg = this.convertStrTosvg(updatedSvg)
        return newSvg;
      },
      // 4. 转换回 SVG XML
      jsonToSvg(json) {
        let svg = `<svg width="${json.width}" height="${json.height}" viewBox="${json.viewBox}" xmlns="${json.xmlns}">\n`;
        json.children.forEach(child => {
          svg += `  <${child.tag}`;
          for (const [attr, value] of Object.entries(child.attrs)) {
            svg += ` ${attr}="${value}"`;
          }
          svg += `>${child.content}</${child.tag}>\n`;
        });
        svg += `</svg>`;
        return svg;
      },

      open_new() {
        // window.showtopology.open({"pens":[]});
        let idval = this.currentbuildInfo.buildingId
        if (typeof(idval) != "undefined"){
          this.$api.okhttp({
            url: this.$http.adornUrl("/topologies/findbybuildId"),
            method: "get",
            params: this.$http.adornParams({
              id: idval,
              customerId: this.$util.cookies.get("customer_id")
            })
          }).then((data) => {
            if (data && data.code === 0 && data.obj) {
              window.showtopology.open(JSON.parse(data.obj.data))
            } else{
              window.showtopology.open({"pens":[]})
            }
          });
        }
      },

      selectBuild (data, checked, indeterminate) {
        if(checked){
          this.$refs.buildTree.setCheckedNodes([]);
          this.currentbuildInfo = data;
          this.$refs.buildTree.setChecked(data.buildingId,checked);
          this.showTree = false
          this.open();
        }
      },
      deptogglePanel (event) {
        event || (event = window.event)
        event.stopPropagation
          ? event.stopPropagation()
          : (event.cancelBubble = true)
        this.showTree ? this.dephide() : this.depshow()
      },
      depshow () {
        this.showTree = true;
        document.addEventListener('click', this.dephidePanel, false)
      },
      dephide () {
        this.showTree = false
        document.addEventListener('click', this.dephidePanel, false)
      },
      dephidePanel (e) {
        if (
          this.$refs.suoShuMenTree &&
          !this.$refs.suoShuMenTree.contains(e.target)
        ) {
          this.dephide()
        }
      },

      async getBuildings() {
        let user = util.cookies.get('user')
        user = JSON.parse(user)
        // console.log(user)
        let project = util.cookies.get('project')
        project = JSON.parse(project)
        const data = await this.$api.getBuildings({
          page: 1,
          limit: 100000,
          customerId: user.customer_id,
          projectid: project.projectId,
          t: Date.now()
        })
        // console.log(res)
        // const getTreeData = list2tree({
        //   idKey: 'buildingId',
        //   parentIdKey: 'parentBuildingId'
        // })
        // const buildings = getTreeData(res.menuList)
        // // console.log(buildings)
        // this.buildings = buildings

        if (data && data.code === 0) {

          this.dataList = Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
          if(this.search){
            this.currentbuildInfo = (data.menuList&&data.menuList.length>0)?data.menuList.find(item=>item.parentBuildingId==-1):{};
            this.selectBuild(this.currentbuildInfo,true);
          }
          else{
            this.currentbuildInfo = (data.menuList&&data.menuList.length>0)?data.menuList.find(item=>item.parentBuildingId==-1):{};
          }
          this.$nextTick(() => {
             this.open();
          })
        } else {
          this.dataList = [];
        }

      },
		},
	}
</script>

<style>
  .objectTree1 {
    margin-left: 65px;
    position: absolute;
    overflow: auto;
    z-index: 100;
    height: 300px;
    /* border: 1px solid #ddd; */
    line-height: normal;
    z-index: 1204;
    box-shadow: 0px 0px 1px 1px #e2dfdf;
    margin-top: 327px;
    border-radius: 4px;
    background-color: white;
  }
  .w-1601{
    width: 535px
  }
</style>
